import { createRouter, createWebHistory } from 'vue-router'
// import Home from '../views/manager/Home.vue'
// import VueRouter from 'vue-router'
// import ManagerLayout from '../views/ManagerLayout.vue'

// const routes = [
//   {path: '/manager', name: 'manager', component: () => import('../views/manager/Home.vue')
//   },
// ]

const routes = [
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register.vue')
  },
  {path: '/login', name: 'login', component: () => import('../views/Login.vue')},
  {
    path: '/manager',
    name: 'manager',
    component: () => import('../views/ManagerLayout.vue'),
    children: [
      {
        path: 'home',
        name: 'manager-home', // 建议添加唯一的 name
        component: () => import('../views/manager/Home.vue')
      },
      {
        path: 'admin',
        name: 'manager-admin', // 建议添加唯一的 name
        component: () => import('../views/manager/Admin.vue')
      },
      {
        path: 'user',
        name: 'manager-user', // 建议添加唯一的 name
        component: () => import('../views/manager/User.vue')
      },
      {
        path: 'about',
        name: 'manager-about', // 建议添加唯一的 name
        component: () => import('../views/manager/About.vue')
      },
      {
        path: 'grade',
        name: 'manager-grade', // 建议添加唯一的 name
        component: () => import('../views/manager/Grade.vue')
      }
    ]
  },
  {
    path: '/',
    redirect: '/login' // 访问根路径时重定向到登录页
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 🔥 路由守卫
router.beforeEach((to, from, next) => {
  const user = localStorage.getItem('user'); // 假设登录状态保存在 localStorage

  // 需要认证的页面，但用户未登录
  if (to.meta.requiresAuth && !user) {
    return next('/login');
  }

  // 已登录用户访问登录或注册页时重定向
  if (user && (to.path === '/login' || to.path === '/register')) {
    return next('/manager/home');
  }

  next();
});

export default router